//
//  HSTypeManagedViewController.m
//  hsdyOrderSystem
//
//  Created by XunFengKJ on 2017/11/9.
//  Copyright © 2017年 赖国锋. All rights reserved.
//

#import "HSTypeManagedViewController.h"
#import "Goods.h"
#import "HSAddTypeVC.h"
#import "XRDragTableView.h"
#import "HSTypeDetailViewController.h"
#import "HSTypeManagedCell.h"
#import "HSFoodtypeModel.h"

static NSString *cellIndentifi = @"typeManagedCell";

@interface HSTypeManagedViewController ()
@property (nonatomic, strong) XRDragTableView *dragTableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong)UILabel *allTypeLabel;//全部
@property (nonatomic, strong)UIView *headerCotainView ;
@end

@implementation HSTypeManagedViewController
-(void)dealloc{
    lNOTIF_REMV();
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"分类管理";
    [self setUpBarButtonItems];
    lNOTIF_ADD(@"foodtypeAddSuccessNotification", foodtypeAddSuccessNotification);
    [self startPullDownRefreshing];
}
-(void)foodtypeAddSuccessNotification{
    LGFLog(@"添加type成功");
    [self loadDataSource];
}

-(void)initViews{
    [self initTableView];
    
}

-(void)loadDataSource{
    [self.dataArray removeAllObjects];
    WEAKSELF
    [XFPostRequest postShopFootTypeshopId:[BookShareUserInforDefault readUserUid] success:^(id responseObject) {
        if ([responseObject[@"status"] intValue] == 200){
            [weakSelf addToDataSource:[HSFoodtypeModel mj_objectArrayWithKeyValuesArray:responseObject[@"content"]]];
            LGFLog(@"responseObject - %@",responseObject);
            HSFoodtypeModel *allModel = weakSelf.dataSource[0];
            self.headerCotainView.tag = allModel.type_id+1200;
            [weakSelf.dataSource removeObjectAtIndex:0];
            [weakSelf.dataArray addObjectsFromArray:self.dataSource];
        }
        else {
            if (![[HSFoodtypeModel mj_objectArrayWithKeyValuesArray:responseObject[@"content"]] isKindOfClass:[NSArray class]]) {
                [weakSelf.dataSource removeAllObjects];
                [weakSelf reloadDataWithBlank];
            }
            [weakSelf setIsPageEnd:YES];
        }
        [weakSelf.dragTableView.mj_header endRefreshing];
        [weakSelf.dragTableView reloadData];
    } failure:^(NSError *error) {
        [weakSelf hideLoading];
        [MBProgressHUD showError:LNETWORKERROR];
        LGFLog(@"error = %@",error);
    }];
}

//点击了全部
-(void)touchAlltypeView{
    LGFLog(@"self.headerCotainView.tag = %zd",self.headerCotainView.tag);
}

-(void)initTableView{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60)];
    
    headerView.backgroundColor = LCOLOROFBACK;
    UIView *headerCotainView = [[UIView alloc] initWithFrame:CGRectMake(0, 9, SCREEN_WIDTH, 50)];
    self.headerCotainView = headerCotainView;
    headerCotainView.backgroundColor = lColorWhite;
    [headerView addSubview:headerCotainView];
    [self.view addSubview:headerView];
    WEAKSELF
    [headerCotainView addTouches:^{
        [weakSelf touchAlltypeView];
    }];
    
    UIImageView *iconImageV = [UIImageView new];
//    iconImageV.backgroundColor = [UIColor blueColor];
    iconImageV.image = [UIImage imageNamed:@"dianhua"];
    [headerView addSubview:iconImageV];
    [iconImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(headerView);
        make.left.equalTo(headerView).offset(16);
        make.height.width.mas_equalTo(30);
    }];
    
    UILabel *allTypeLabel = [UILabel new];
    self.allTypeLabel = allTypeLabel;
    [headerView addSubview:allTypeLabel];
    allTypeLabel.font = FONT(16);
    allTypeLabel.text = @"全部";
    [allTypeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(headerView);
        make.left.equalTo(iconImageV.mas_right).offset(6);
    }];
    
    
    self.dragTableView = [[XRDragTableView alloc] init];
    [self.dragTableView registerNib:[UINib nibWithNibName:NSStringFromClass([HSTypeManagedCell class]) bundle:nil] forCellReuseIdentifier:cellIndentifi];
    self.dragTableView.backgroundColor = LCOLOROFBACK;
    self.dragTableView.dataArray = self.dataArray;
    self.dragTableView.delegate =self;
    self.dragTableView.dataSource =self;
    //当cell拖动到tableView边缘时，tableView自动滚动的速度
    self.dragTableView.scrollSpeed = 10;
    //    [self initTableViewWithStyle:UITableViewStylePlain];
    [self.view addSubview:self.dragTableView];
    [self.dragTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(60);
        make.left.right.bottom.equalTo(self.view);
    }];
    self.dragTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRereshing)];
    [self.dragTableView.mj_header beginRefreshing];

    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 70)];
    footerView.backgroundColor = LCOLOROFBACK;
    UILabel *tipLabel = [UILabel new];
    [footerView addSubview:tipLabel];
    tipLabel.numberOfLines = 0;
    tipLabel.font = FONT(13);
    tipLabel.text = @"温馨提示：\n长按分类拖动即可排序";
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@5);
        make.left.equalTo(@12);
    }];
    self.dragTableView.tableFooterView = footerView;
    //拖拽后的结果回调
//    WEAKSELF
    self.dragTableView.insertCompleteBlock = ^(NSMutableArray *insertResultDataArray) {
//        LGFLog(@"插入完成:%@",insertResultDataArray);
        NSMutableArray *idArr = @[].mutableCopy;
        [idArr addObject:[NSString stringWithFormat:@"%zd",self.headerCotainView.tag-1200]];
        for (int i = 0; i<insertResultDataArray.count; i++) {
            HSFoodtypeModel *model = insertResultDataArray[i];
            [idArr addObject:[NSString stringWithFormat:@"%zd",model.type_id]];
        }
        LGFLog(@"传过去%@",idArr);
        [weakSelf postSortdataArr:[NSArray matchingStringWithDataArr:idArr]];
    };
}
//排序
-(void)postSortdataArr:(NSString *)insertResultDataArray{
   WEAKSELF
        [self showLoadingWithClear:YES];
        [XFPostRequest postShopFootTypeUpdateSortshopId:[BookShareUserInforDefault readUserUid] shopItemIds:insertResultDataArray success:^(id responseObject) {
            [weakSelf hideLoading];
            
            if ([responseObject[@"status"] intValue] == 200){
                [SOAutoHideMessageView showMessage:[responseObject safeJsonObjectForKey:@"msg"] inView:weakSelf.view];
                lNOTIF_POST(@"foodtypeAddSuccessNotification", nil);
//                [weakSelf loadDataSource];
            }
            LGFLog(@"插入完成 -- %@",responseObject);
        } failure:^(NSError *error) {
            LGFLog(@"插入完成 -- %@",error);
        }];
//    }];
}

//下拉刷新
-(void)headerRereshing{
    self.requestCurrentPage = 1;
    [self loadDataSource];
}

//-(void)loadDataSource{
//    [self.dragTableView.mj_header endRefreshing];
//}

#pragma mark - UITableView DataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HSTypeManagedCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifi];
    
    if (self.dataArray.count) {
        HSFoodtypeModel *model = self.dataArray[indexPath.row];
        cell.model =model;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    WEAKSELF
    cell.delBtnClickblock = ^(NSInteger btnTag) {
        [weakSelf postDelWithType_id:btnTag];
    };
    return cell;
}
//删除
-(void)postDelWithType_id:(NSInteger)type_id{

    
    WEAKSELF
    [UIAlertController alertControllerShowInController:self Title:@"提示" message:@"是否删除？" cancelBlock:^{
       
    } checkBlock:^{
        [XFPostRequest postShopFootTypeDeleteShopFoodItemshopId:[BookShareUserInforDefault readUserUid] type_id:lIntToString(type_id) success:^(id responseObject) {
            LGFLog(@"responseObject = %@",responseObject);
            if ([responseObject[@"status"] intValue] == 200){
                [weakSelf loadDataSource];
                [SOAutoHideMessageView showMessage:[responseObject safeJsonObjectForKey:@"msg"] inView:weakSelf.view];
                lNOTIF_POST(@"foodtypeDelSuccessNotification", nil);
            }
        } failure:^(NSError *error) {
            LGFLog(@"error = %@",error);
        }];
    }];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}

-(void)setUpBarButtonItems{
    UIButton* rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 80, 40);
    [rightBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 15, 0, -15)];
    [rightBtn setTitle:@"添加分类" forState:UIControlStateNormal];
    rightBtn.titleLabel.font = FONT(14);
    [rightBtn addTarget:self action:@selector(rightBtnItemClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc] initWithCustomView:rightBtn];
}

#pragma mark - 添加分类
-(void)rightBtnItemClick{
    
    HSAddTypeVC *addtype = [HSAddTypeVC new];
    [self.navigationController pushViewController:addtype animated:YES];
}
#pragma mark - lazy
- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];//[NSMutableArray arrayWithObjects:@"a", @"b", @"c", @"d", nil];
    }
    return _dataArray;
}

@end
